﻿Imports System.DirectoryServices

Public Class GetBdeKeys
    Private Structure BitlockerInfo
        Dim RecoveryPassword As String
        Dim DistinguishedName As String
        Dim WhenCreated As Date
        Dim WhenChanged As Date
    End Structure

    Public Shared Function ReturnRecoveryKey(ByVal strComputerObjectLdap As String)
        Dim res As String
        ' ReSharper disable once RedundantAssignment
        res = "No bitlocker key registered with Active Directory"
        Try
            Dim objSearch As New DirectorySearcher()
            objSearch.SearchRoot = New DirectoryEntry(strComputerObjectLdap)
            objSearch.PageSize = "1000"
            objSearch.Filter = "(&(objectClass=msFVE-RecoveryInformation))"
            objSearch.SearchScope = SearchScope.Subtree

            Dim colQueryResults As SearchResultCollection
            colQueryResults = objSearch.FindAll()
            ' ReSharper disable once RedundantAssignment
            Dim objResult As SearchResult = Nothing
            ' ReSharper disable once NotAccessedVariable
            Dim strBitLockerInfo As BitlockerInfo = New BitlockerInfo
            For Each objResult In colQueryResults
                If objResult.Properties.Contains("msFVE-RecoveryPassword") Then
                    strBitLockerInfo.RecoveryPassword = (objResult.Properties("msFVE-RecoveryPassword")(0))
                End If
                If objResult.Properties.Contains("whencreated") Then
                    strBitLockerInfo.WhenCreated = (objResult.Properties("whencreated")(0))
                End If
                If objResult.Properties.Contains("whenchanged") Then
                    strBitLockerInfo.WhenChanged = (objResult.Properties("whenchanged")(0))
                End If
                If objResult.Properties.Contains("distinguishedname") Then
                    strBitLockerInfo.DistinguishedName = (objResult.Properties("distinguishedname")(0))
                End If
            Next
            res = strBitLockerInfo.RecoveryPassword
            Return res
        Catch ex As Exception
            Return "No bitlocker key registered with Active Directory"
        End Try
    End Function
End Class
